package com.example.vv.model.chat.base.presenter;

import com.example.vv.frameWork.entity.ChatEntity;
import com.example.vv.frameWork.mvp.MvpPresenter;
import com.example.vv.frameWork.mvp.ViewISNullException;
import com.example.vv.model.chat.base.contract.ChatContract;
import com.example.vv.model.chat.base.model.ChatModel;
import com.example.vv.req.REQ_CHAT;
import com.example.vv.res.BaseRespont;
import com.google.gson.Gson;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class ChatPresenter extends MvpPresenter<ChatContract.View, ChatContract.Model> implements ChatContract.Presenter {
    private int page=0;
    public boolean isFlush=true;
    @Override
    public void attach(ChatContract.View view) {
        super.attach(view);
        model=new ChatModel();
    }
    public void load(){
        page+=1;
        isFlush=false;
        req_ChatList();
    }
    public void reflush(){
        page=0;
        isFlush=true;
        req_ChatList();
    }
    public void req_ChatList(){
        model.POST_API_CHAT(new REQ_CHAT(String.valueOf(page)))
                .map(new Function<BaseRespont, ChatEntity>() {
                    @Override
                    public ChatEntity apply(BaseRespont baseRespont) throws Exception {
                        return new Gson().fromJson(baseRespont.getBaseData(),ChatEntity.class);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ChatEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ChatEntity chatEntity) {
                        try {
                            view().setChatList(chatEntity);
                        } catch (ViewISNullException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
